package com.ms.base.web.error;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;

/**
 * <b>description</b>： <br>
 * <b>time</b>：2018-08-14 15:31 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class GlobalErrorViewResolver implements ErrorViewResolver, Ordered, InitializingBean {

    private Map<HttpStatus.Series, String> seriesViews;
    /**
     * 状态4xx对应的viewname
     */
    @Value("${com.ms.base.web.error.view.name.4xx:other/4xx}")
    private String viewName4xx = "other/4xx";

    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        String view = seriesViews.get(status.series());
        if (StringUtils.isNotBlank(view)) {
            return new ModelAndView(view, model);
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<HttpStatus.Series, String> views = new EnumMap<>(HttpStatus.Series.class);
        views.put(HttpStatus.Series.CLIENT_ERROR, viewName4xx);
        seriesViews = Collections.unmodifiableMap(views);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
